<?php

namespace App\Http\Controllers;

use App\Exceptions\AuthException;
use App\Models\ZZMed\ZHospMember;
use App\Services\AuthService;
use App\Traits\ResponseFormat;
use App\Traits\SmsHelper;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, ResponseFormat, SmsHelper;

    /**
     * 根据header头里的信息判定所传应用信息
     * @param Request $request
     * @param string $key ex:app_id, app_name, app_version
     * @return string
     * @throws \Exception
     */
    protected function getClientAppInfo(Request $request, $key = '')
    {
        if (!$appInfo = $request->header('X-ZZ-APP-INFO')) {
            //throw new \Exception('Cannot find the header, header like [X-ZZ-APP-INFO]!');
        }

        $appInfos = json_decode($appInfo, true);

        if (!$key) {
            return $appInfos;
        }

        $appInfoKeys = [
            'zz_app_id',
            'zz_app_name',
            'zz_app_version',
        ];

        if (!in_array($key, $appInfoKeys)) {
            throw new \Exception('Cannot find the param key, value like [' . $key . ']!');
        }

        return isset($appInfos[$key]) ? $appInfos[$key] : '';
    }


    /**
     * 获取登录用户信息 默认是guard:api
     *
     * @param string $guard
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     * @throws AuthException
     */
    protected function authUser($guard = 'api')
    {
        $user = auth(AuthService::getGuard())->user();
        if (!$user) {
            throw new AuthException('Cannot find the auth user when get user by auth!');
        }
        return $user;
    }

}
